<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :class-name="'sub-navbar '+postForm.status">
        <CommentDropdown v-model="postForm.comment_disabled" />
        <PlatformDropdown v-model="postForm.platforms" />
        <SourceUrlDropdown v-model="postForm.source_uri" />
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">发布
        </el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">草稿</el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>

          <Warning />

          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.name" :maxlength="100" name="name" required>班级名称</MDinput>
            </el-form-item>
            <el-row>
              <el-form-item label-width="50px" label="分类:" style="margin-bottom: 40px;" prop="title">
                <el-select v-model="rootCatagory" clearable placeholder="请选择分类">
                  <el-option
                    v-for="item in classesCategory"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"/>
                </el-select>
                <el-select v-model="postForm.category_id" clearable placeholder="请选择分类">
                  <el-option
                    v-for="item in classesCategoryChildren"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-row>
            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="50px" label="名称:" class="postInfo-container-item">
                    <el-select v-model="postForm.user" :remote-method="getRemoteUserList" filterable remote placeholder="搜索用户">
                      <el-option v-for="(item,index) in userListOptions" :key="item+index" :label="item" :value="item"/>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label-width="80px" label="发布时间:" class="postInfo-container-item">
                    <el-date-picker v-model="postForm.create_time" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"/>
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="60px" label="重要性:" class="postInfo-container-item">
                    <el-rate
                      v-model="postForm.importance"
                      :max="3"
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                      :low-threshold="1"
                      :high-threshold="3"
                      style="margin-top:8px;"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin-bottom: 40px;" label-width="45px" label="摘要:">
          <el-input :rows="1" v-model="postForm.info" type="textarea" class="article-textarea" autosize placeholder="请输入内容"/>
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}字</span>
        </el-form-item>

        <div class="editor-container">
          <Tinymce ref="editor" :height="400" v-model="postForm.info" />
        </div>

        <div style="margin-bottom: 20px;">
          <Upload v-model="postForm.avatar" />
        </div>
      </div>
    </el-form>

  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/singleImage3'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
// import { validateURL } from '@/utils/validate'
import { fetchClasses, storeClasses, updateArticle, getClassesCategory } from '@/api/classes'
import { userSearch } from '@/api/remoteSearch'
import Warning from './components/Warning'
import { CommentDropdown, PlatformDropdown, SourceUrlDropdown } from './components/Dropdown'

const defaultForm = {
  id: null,
  user_id: '',
  is_vip: '',
  college_id: '',
  category_id: '', // 班级类别
  avatar: '', // 班级封面
  name: '', // 班级介绍
  info: '', // 班级介绍
  active: '', // 活跃度
  browse: '', // 浏览量
  num: ''
}

export default {
  name: 'ClassesDetail',
  components: { Tinymce, MDinput, Upload, Sticky, Warning, CommentDropdown, PlatformDropdown, SourceUrlDropdown },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    // const validateSourceUri = (rule, value, callback) => {
    //   if (value) {
    //     if (validateURL(value)) {
    //       callback()
    //     } else {
    //       this.$message({
    //         message: '外链url填写不正确',
    //         type: 'error'
    //       })
    //       callback(new Error('外链url填写不正确'))
    //     }
    //   } else {
    //     callback()
    //   }
    // }
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rules: {
        name: [{ validator: validateRequire }],
        category_id: [{ validator: validateRequire }],
        info: [{ validator: validateRequire }]
      },
      tempRoute: {},
      classesCategory: [], // 班级分类列表
      classesCategoryChildren: [],
      childrenCatagory: '',
      rootCatagory: ''
    }
  },
  computed: {
    contentShortLength() { // 计算属性计算输入字符的长度
      return this.postForm.info.length
    },
    lang() {
      return this.$store.getters.language
    }
  },
  watch: {
    rootCatagory: function(val) {
      if (val) {
        this.getClassesCategoryRoot(val, 1)
      }
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
    this.getClassesCategoryRoot(0, 0)
    // Why need to make a copy of this.$route here? 我們需要在这里复制一份路由出来
    // 因为如果输入此页面并快速切换标记，则可能在执行setTagsViewTitle函数时，this.$route不再指向当前页面
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    getClassesCategoryRoot(pid, isRoot) {
      if (isRoot === 0) {
        return getClassesCategory(pid).then(res => {
          this.classesCategory = res.data.data
        }).catch(error => {
          console.log(error)
        })
      } else if (isRoot === 1) {
        return getClassesCategory(pid).then(res => {
          this.classesCategoryChildren = res.data.data
        }).catch(error => {
          console.log(error)
        })
      }
    },
    fetchData(id) {
      fetchClasses(id).then(response => {
        this.postForm = response.data.data
        // Just for test
        this.postForm.name = `${this.postForm.name}`
        this.postForm.content_short += `${this.postForm.id}`

        // Set tagsview title
        this.setTagsViewTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '编辑文章' : 'Edit Article'
      const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
      this.$store.dispatch('updateVisitedView', route)
    },
    submitForm() {
      // this.postForm.display_time = parseInt(this.display_time / 1000)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isEdit) {
            updateArticle(this.postForm).then(response => {
              // const ret = response
              // Set tagsview titl
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
              this.setTagsViewTitle()
            }).catch(err => {
              console.log(err)
              this.$notify({
                title: '验证失败',
                message: err.message,
                type: 'error',
                duration: 2000
              })
            })
          } else {
            storeClasses(this.postForm).then(response => {
              // const ret = response
              // Set tagsview titl
              this.$notify({
                title: '成功',
                message: '发布成功',
                type: 'success',
                duration: 2000
              })
              this.setTagsViewTitle()
            }).catch(err => {
              console.log(err)
              this.$notify({
                title: '验证失败',
                message: err.message,
                type: 'error',
                duration: 2000
              })
            })
          }

          this.postForm.is_delete = 'published'
          this.loading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (this.postForm.info.length === 0 || this.postForm.name.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.$message({
        message: '保存成功',
        type: 'success',
        showClose: true,
        duration: 1000
      })
      this.postForm.status = 'draft'
    },
    getRemoteUserList(query) {
      userSearch(query).then(response => {
        if (!response.data.items) return
        this.userListOptions = response.data.items.map(v => v.name)
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "../../styles/mixin.scss";
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
    .editor-container {
      min-height: 500px;
      margin: 0 0 30px;
      .editor-upload-btn-container {
        text-align: right;
        margin-right: 10px;
        .editor-upload-btn {
          display: inline-block;
        }
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
}
</style>
